package cn.jfast.framework.web.filter;

import cn.jfast.framework.web.api.ApiContext;
import cn.jfast.framework.web.api.HttpRequest;
import cn.jfast.framework.web.api.HttpResponse;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(filterName = "restful",
        urlPatterns = {"/*"},
        dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD})
public class RestfulFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
        String contextPath = filterConfig.getServletContext().getContextPath();
        ApiContext.APP_HOST_PATH_LENGTH = (contextPath == null || "/".equals(contextPath) ? 0
                : contextPath.length());
        ApiContext.loadContext();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 
    	if (!(servletRequest instanceof HttpServletRequest)
                || !(servletResponse instanceof HttpServletResponse))
            throw new ServletException("no HTTP request");
    	HttpRequest request = new HttpRequest((HttpServletRequest)servletRequest);
        HttpResponse response = new HttpResponse((HttpServletResponse)servletResponse);
        if(!ApiContext.handlerResources(request, response)
                && !ApiContext.handlerApi(request, response))
            filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {

    }

}
